package net.loststone

class IniciController {

    def index = {
        Town ejpana = Town.findByGov_id(0)
        def indicadorEconomic = EconInfo.findAllByAfecta(ejpana)

        // llista de ccaa
        def level1 = Town.findAllByParent(ejpana)

        // llista provincies + indicador economic de la ccaa.
        def level2 = null;
        Town selected_state = null;
        if (params.state_id) {
            indicadorEconomic = null;
            selected_state = Town.findByIdAndType(params.state_id, "state")
            level2 = Town.findAllByParent(selected_state)
            def nowIndicadorEconomic = EconInfo.findAllByAfecta(selected_state)
            if (nowIndicadorEconomic) {
                indicadorEconomic = nowIndicadorEconomic;
            }
        }

        // agafem llista de pobles + indicador economic de la provincia.
        def level3 = null;
        Town selected_province = null;
        if (params.province_id) {
            // agafa la ccaa pare.
            indicadorEconomic = null;

            selected_province = Town.findByIdAndType(params.province_id, "province")
            level2 = Town.findAllByParent(selected_province.parent)
            level3 = Town.findAllByParent(selected_province)
            def nowIndicadorEconomic = EconInfo.findAllByAfecta(selected_province)
            if (nowIndicadorEconomic) {
                indicadorEconomic = nowIndicadorEconomic;
            }
            
        }

        // agafem les dades de la ciutat.
        Town selected_town = null;
        if (params.town_id) {
            indicadorEconomic = null;

            selected_town = Town.findByIdAndType(params.town_id, "town")
            level3 = Town.findAllByParent(selected_town.parent)
            level2 = Town.findAllByParent(selected_town.parent.parent)
            def nowIndicadorEconomic = EconInfo.findAllByAfecta(selected_town)
            if (nowIndicadorEconomic) {
                indicadorEconomic = nowIndicadorEconomic;
            }
        }

        [states: level1, provinces: level2, towns: level3, indicadors_economics : indicadorEconomic,
            state : selected_state, province : selected_province, town : selected_town]
    }

}